<template>
  <div style="height:100%;">
    <div class="table-header" v-if="false">
      <div class="table-info">
        <span class="info-box">
          <span>司机：</span>
          <span class="info-value">{{ currentIdxDetail.driverName || '无' }}</span>
        </span>
        <span class="info-box">
          <span>车次：</span>
          <span class="info-value">{{ currentIdxDetail.trainNum || '无' }}</span>
        </span>
        <span class="info-box">
          <span>日期：</span>
          <span class="info-value">{{ currentIdxDetail.date || '无' }}</span>
        </span>
      </div>
    </div>
    <div class="table-content">
      <div style="padding: 10px 0; display: flex; align-items: center; ">
        <el-button size="mini" type="plain" @click="download" :disabled="batchFile.loading" :icon="batchFile.loading ? 'el-icon-loading' : 'el-icon-download'">{{ batchFile.loading ? '下载中....' : '下载' }}</el-button>
        <el-button size="mini" type="plain" @click="handleExcelDownload" :disabled="downloadLoading" :icon="downloadLoading ? 'el-icon-loading' : 'el-icon-download'">{{ downloadLoading ? '正在导出....' : '导出全量项点' }}</el-button>
      </div>
      <el-table-extends :data="tableList" border height="calc(100% - 40px)" ref="mainTable" size="mini" class="mainTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center;" :selectable="(row) => !!row.handFile" />
        <el-table-column label="序号" show-overflow-tooltip type="index" align="center" :index="indexMethod" />
        <el-table-column prop="name" label="项点名称" show-overflow-tooltip width="150">
          <template slot="header" slot-scope="scope">
            <div class="select-box">
              <el-select :scope="scope" v-model="searchText" placeholder="项点名称" @change="nameChange" size="mini" style="width: 100%;">
                <el-option v-for="(item, index) in phaseNames" :key="index" :label="item.label" :value="item.value">
                  <span style="float: left; ">{{ item.label }}</span>
                  <span style="float: right; color: green; font-size: 13px; margin-left: 12px; font-weight: bold;">{{ item.count }}</span>
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="代码" prop="code" show-overflow-tooltip width="80" />
        <el-table-column label="信号机类型" prop="type" align="center" show-overflow-tooltip width="85" />
        <el-table-column label="开始时间" prop="startTime" align="center" show-overflow-tooltip width="140" />
        <el-table-column label="结束时间" prop="endTime" align="center" show-overflow-tooltip width="140" />
        <el-table-column label="状态" prop="illegalText" align="center" show-overflow-tooltip width="145">
          <template slot="header" slot-scope="scope">
            <div class="select-box">
              <el-select :scope="scope" v-model="typeActive" placeholder="状态" size="mini" style="width: 100%;" @change="nameChange">
                <el-option v-for="(item, index) in handPhaseStatusList" :key="index" :label="item.label" :value="item.label">
                  <span style="float: left; ">{{ item.label }}</span>
                  <span style="float: right; color: green; font-size: 13px; margin-left: 12px; font-weight: bold;">{{ item.count }}</span>
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="手势地址"
          align="center"
          class-name="handleLook"
        >
          <template slot-scope="scope">
            <div
              v-if="scope.row.handFile"
              :content="scope.row.handFile"
              style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; "
              @click="lookItem(scope.row)"
            >
              <a
                :href="'#'+scope.row.handFile+scope.$index"
                target="view_frame"
              > 视频 </a>
            </div>
          </template>
        </el-table-column>-->
        <el-table-column label="动作定位" align="center" class-name="handleLook">
          <template slot-scope="scope">
            <!-- <el-tooltip
              :content="scope.row.confirmFile"
              placement="top"
              v-if="scope.row.confirmFile"
            >
              <div
                style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; "
                @click="lookActionItem(scope.row)"
              >
                <a
                  :href="'#'+scope.row.confirmFile+scope.$index"
                  target="view_frame"
                > 点击查看 </a>
              </div>
            </el-tooltip>-->
            <div :content="scope.row.confirmFile" v-if="scope.row.confirmFile" style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; " @click="lookActionItem(scope.row)">
              <a :href="'#'+scope.row.confirmFile" target="view_frame">点击查看</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button @click="redirectToVideo(scope.row)" size="small" style="color: #409eff;" type="text">视频定位</el-button>
            <el-button @click="openComments(scope.row)" size="small" :style="`color: ${scope.row.phaseSign ? 'red' : '#409eff'}`" type="text">复核</el-button>
          </template>
        </el-table-column>
      </el-table-extends>
      <el-pagination style="padding-top:6px;" @size-change="page.setSize($event)" @current-change="page.setCurrent($event)" :current-page="page.current" :page-sizes="page.sizes" :page-size="15" layout="total, sizes, prev, pager, next, jumper" :total="page.total" />
    </div>
    <comment title="分析意见" :visible.sync="isComment" :idx-detail="currentIdxDetail" :load-analysis-form="loadAnalysisForm" :phases="selectedPhase" @submit="submitComments" />
    <div style="display: none;">
      <frameset>
        <frame name="view_frame" />
      </frameset>
    </div>
  </div>
</template>
<script>
// import { Handle } from '@/store/modules/handle/mixins';
import convert from '@/utils/convert';
// import Comment from '@/views/analysis/lkj/components/Comment.vue';
// import { BatchFile } from '@/facade/download';
// import { formatJson } from '@/utils';
// import { exportJson2Excel } from '@/utils/excel';
// import { handAllList, handList } from '@/api/handle';
// import { DictModule } from '@/store/modules/dict';
export default {
  data(){
    return{
      info:{},
      index: 0,
      ids: [],
      codeObj: {
        H:'手势'
      },
      typeActive:'全部状态',
      downloadLoading:false,
      isComment: false,
      form: {
        item: '',
        content: '',
        question: '',
        opinion: '',
        illegal: ''
      },
      selectedPhase: [],
      searchText: '',
      tableAllData: [],
      selectionList: [],
      batchFile: ''
    }
  },
  props:{
    currentIdxDetail: {
      type: Object,
      default() {
        return {};
      }
    },
    analysisPhaseList: {
      type: Array,
      default() {
        return [];
      }
    },
    loadAnalysisForm: {
      type: Function,
      default(params) {
        return params;
      }
    },
    lkjId:{
      type: String,
      default() {
        return '';
      }
    }
  },
  computed: {
    page: {
      get(){
        return this.hand;
      }
    },
    tableData: {
      get(){
        return this.handList || [];
      }
    },
    tableRes: {
      get(){
        return this.handRes || {};
      }
    },
    phaseNames: {
      get(){
        const names = this.tableData.map((t) => t.name);
        const nameList = [...new Set(names)];
        nameList.sort((a, b) => {
          return a.length - b.length;
        });
        const list = nameList.map((label) => {
          return {
            label,
            value: label,
            count: names.filter((name) => name === label).length
          };
        });
        const arr = this.tableRes.handPhaseCount || [];
        let sum = 0;
        const phaseCounts = arr.map((item) => {
          sum += item.num;
          return {
            label: item.name,
            value: item.name,
            count: item.num
          };
        });
        phaseCounts.unshift({
          label: '全部项点',
          value: '',
          count: sum
        });
        return phaseCounts;
      }
    },
    handPhaseStatusList:{
      get(){
        const arr = this.tableRes.handPhaseStatusList || [];
        let sum = 0;
        const phaseStatusList = arr.map((item) => {
          sum += item.num;
          return {
            label: DictModule.phaseStatusMap[+item.key],
            value: DictModule.phaseStatusMap[+item.key],
            count: item.num
          };
        });
        phaseStatusList.unshift({
          label: '全部状态',
          value: '',
          count: sum
        });
        console.log('phaseStatusList', phaseStatusList);
        return phaseStatusList;
      }
    },
    tableList:{
      get(){
        const list = this.tableData.filter(
          (t) => !this.searchText || t.name === this.searchText
        );
        return this.tableData;
      }
    }
  },
  methods: {
    getAllTableData() {
      // handAllList({ recordId: this.currentIdxDetail.recordId }).then(
      //   (res) => {
      //     this.tableAllData =
      //       res.data.map((item) => {
      //         return Object.assign({}, item, {
      //           startTime: convert.dateFormat(
      //             new Date(item.startTime),
      //             'yyyy-MM-dd HH:mm:ss'
      //           ),
      //           endTime: convert.dateFormat(
      //             new Date(item.endTime),
      //             'yyyy-MM-dd HH:mm:ss'
      //           ),
      //           code: this.codeObj[item.code],
      //           illegalText: DictModule.phaseStatusMap[item.illegal]
      //         });
      //       }) || [];
      //     console.log(this.tableAllData);
      //   }
      // );
    },
    lookItem(row){
      this.$emit('look-item',row)
    },
    lookActionItem(row){
      this.$emit('look-action-item',row)
    },
    openComments(row) {
      this.selectedPhase = [];
      const phase = this.analysisPhaseList.find(
        (phase) => phase.id === row.id
      );
      const phaseItem = { ...phase, id: row.id };
      this.selectedPhase = [phaseItem];
      const illegal = row.illegal;
      this.form = Object.assign({}, this.form, {
        item: phase.id,
        content: '',
        question: '',
        opinion: '',
        illegal
      });
      this.isComment = true;
    },
    getIillegal() {
      let statusTxt = -1;
      switch (this.typeActive) {
        case '全部状态':
          statusTxt = -1;
          break;
        case '违章':
          statusTxt = 0;
          break;
        case '未处理':
          statusTxt = 1;
          break;
        case '视频缺失':
          statusTxt = 2;
          break;
        case '正常':
          statusTxt = 3;
          break;
        case '记录':
          statusTxt = 4;
          break;
        case '提醒':
          statusTxt = 5;
          break;
        case '其他':
          statusTxt = 6;
          break;
        default:
          break;
      }
      return statusTxt;
    },
    nameChange(val) {
      const status = this.getIillegal();
      this.page.setQueryParams({
        recordId: this.currentIdxDetail.recordId,
        illegal: status,
        name: this.searchText,
        current: 1,
        size: 15
      });
      this.hand.query();
      this.page
        .setQueryParams({
          recordId: this.currentIdxDetail.recordId,
          illegal: status,
          name: this.searchText
        })
        .setCurrent(1);
    },
    indexMethod(index) {
      return index + 1 + (this.page.current - 1) * this.page.size;
    },
    redirectToVideo(row){
       this.$emit('redirectToVideo',row)
    },
    submitComments(form){
      this.$emit('submitComments',form)
    },
    download() {
      if (this.selectionList.length <= 0) {
        this.$message.warning('请选择要下载的数据！');
        return false;
      }
      const params = this.selectionList
        .filter((item) => item.handFile)
        .map((item) => {
          return {
            name: `${item.name}-${item.startTime}~${item.endTime}`,
            url: item.handFile,
            suffix: 'mp4'
          };
        });
      this.batchFile.addBatch(params);
    },
    andleExcelDownload() {
      this.getAllTableData();
      if (this.tableAllData.length <= 0) {
        this.$message.warning('请选择要下载的数据！');
        return;
      }
      this.downloadLoading = true;
      const tHeader = [
        '项点名称',
        '代码',
        '信号机类型',
        '开始时间',
        '结束时间',
        '状态',
        '手势地址'
      ];
      const filterVal = [
        'name',
        'code',
        'type',
        'startTime',
        'endTime',
        'illegalText',
        'handFile'
      ];
      const list = this.tableAllData;
      const data = formatJson(filterVal, list);
      exportJson2Excel(
        tHeader,
        data,
        `${this.currentIdxDetail.date}_${this.currentIdxDetail.driverName}`,
        undefined,
        undefined,
        true,
        'xlsx'
      );
      this.downloadLoading = false;
    },
    handleSelectionChange(val) {
      this.selectionList = val;
    }
  },
  mounted() {
    const a = document.createElement('a');
    a.setAttribute('href', '/test/xxx');
    a.setAttribute('target', 'view_frame');
    a.click();
  }
}
</script>

<style scoped>
.table-header {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  height: 50px;
  width: 100%;
}
.table-header .table-info {
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgb(96, 98, 102);
}
.table-header .table-info .info-box {
  margin: 0 20px;
  font-size: large;
  font-weight: bold;
}
.table-header .table-info .info-box .info-value {
  color: rgb(33, 150, 243);
}
.table-header .type-tag {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.table-content {
  height: calc(100% - 50px);
  padding: 0 16px;
}
/deep/.select-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: 0px;
}
/deep/.select-box .el-select {
  padding: 0px;
}
/deep/.select-box .el-select .el-input {
  padding: 0px;
}
.mainTable .handleLook a {
  cursor: pointer;
  color: rgb(64, 158, 255);
}
.mainTable .handleLook a:visited {
  color: rgb(244, 67, 54);
}
</style>

